//
//  ImageListViewController.m
//  reacticons
//
//  Created by Admin on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ImageListViewController.h"

#import "DatabaseConnection.h"
#import "Photo.h"
#import "LoadingView.h"

#import "AppDelegate.h"
#import "ImageDetailViewController.h"
#import "UIGridViewCell+DownloadImage.h"
#import "Utilities.h"
#import "TestFlight.h"
#import "DownloadHelper.h"
#import "MemeCreatorViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Globals.h"
#define STARTING_SAVE_MULTIPLE  1
#define CANCEL_SAVE_MULTIPLE    2
#define CONFIRM_SAVE_MULTIPLE   3
#define OPTIONS_BUTTON          11
#define COPY_BUTTON             12
#define EMAIL_BUTTON            13
#define SMS_BUTTON              14

@interface ImageListViewController (internal)

- (UIImage *)imageAtIndex:(NSUInteger)index;
- (void)popupDidSelectBtnTag:(int)tag;

@end

@implementation ImageListViewController

@synthesize parentID = _parentID;

#pragma mark - View lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [saveMultiToolBar setHidden:YES];
    [saveMultiToolBar setFrame:CGRectMake(0, 0, 320, 44)];

//    UIButton * selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [selectButton setFrame:CGRectMake(0, 0, 46, 26)];
//    [selectButton setTag:STARTING_SAVE_MULTIPLE];
//    [selectButton setBackgroundImage:[UIImage imageNamed:@"right_button.png"] forState:UIControlStateNormal];
//    [selectButton.titleLabel setFont:[UIFont fontWithName:@"Impact" size:12]];
//    [selectButton addTarget:self action:@selector(btnWasClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * saveMultiple = [[UIBarButtonItem alloc] initWithTitle:@"Select" style:UIBarButtonItemStyleBordered target:self action:@selector(btnWasClicked:)];
    [saveMultiple setTag:STARTING_SAVE_MULTIPLE];
    if ([_parentID isEqualToString:@"recentlyUsed"]) {
        [saveMultiple setTitle:@"Clear"];
    }

    [self.navigationItem setRightBarButtonItem:saveMultiple];
    [saveMultiple release];

    isMultipleSelection = NO;
    
    DBLOG(@"parentID:%@",_parentID);
    if ([[_parentID componentsSeparatedByString:@";"] count]>1) {
        self.navigationItem.title=[[_parentID componentsSeparatedByString:@";"] objectAtIndex:1];
    }
    if (![_parentID isEqualToString:@"recentlyAdded"]
        &&![_parentID isEqualToString:@"recentlyUsed"]) 
    {
        imageListArray = [[DatabaseConnection getTumblrPhotosWithTag:_parentID] retain];

    }
    else {
        DBLOG(@"imagelistarray:%d",imageListArray.count);
        if ([_parentID isEqualToString:@"recentlyUsed"]) {
            imageListArray=[[DatabaseConnection getRecentlyUsedPhotos] retain];
        }
        else{
            imageListArray=[[DatabaseConnection getRecentlyAddedPhotos] retain];
        }
    }
    
    DBLOG(@"%d",imageListArray.count);
    
    listOfFlags = [[NSMutableArray alloc] init];
    for (int i = 0; i < imageListArray.count; i++)
        [listOfFlags addObject:@"0"];
    
    gridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
    [gridView setBackgroundColor:[UIColor clearColor]];
    gridView.delegate=self;
    gridView.dataSource=self;
    
    [gridView setAutoresizingMask:UIViewAutoresizingNone];
    [gridView setEnableMultipleSelection:NO];
    [gridView setEnableReOrderring:NO];
    [self.view insertSubview:gridView atIndex:0];

    popUpBar = [[PopUpViewController alloc] init];
    [popUpBar.view setFrame:CGRectMake(0, 0, 72, 34)];
    [popUpBar.view setHidden:YES];
    [popUpBar setDelegate:self];
    [self.view addSubview:popUpBar.view];
    
    //
    //popup label

    
    //


}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [Utilities hideTabBar:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [gridView reloadData];
    [popUpBar.view setHidden:YES];
    [editBar setHidden:YES];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    [Utilities showTabBar:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)btnWasClicked:(id)sender{
    //save multiple =1
    [popUpBar.view setHidden:YES];
    UIActionSheet *actionSheet;
    switch ([sender tag])
    {
        case STARTING_SAVE_MULTIPLE:
            copyBtn.title=@"Copy";

            if ([_parentID isEqualToString:@"recentlyUsed"]){
                if (imageListArray.count ==0) {
                    return;
                }
                self.navigationItem.leftBarButtonItem.enabled=NO;
                NSMutableArray *itemArray=[[NSMutableArray alloc] init];
                for (Photo *photo in imageListArray) {
                    [photo setPhotoRecentlyUsed:@"19990102030405"];
                    [itemArray addObject:[photo itemObject]];
                }
                [DatabaseConnection writeListItems:itemArray toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
                [itemArray release];

                imageListArray=[[DatabaseConnection getRecentlyUsedPhotos] retain];
                self.navigationItem.leftBarButtonItem.enabled=YES;
                [gridView reloadData];
                return;
            }
            [saveBtn setEnabled:NO];
            isMultipleSelection = YES;
            [gridView setEnableMultipleSelection:YES];
            [editBar setHidden:NO];
            [Utilities hideTabBar:self.tabBarController];
            [gridView setFrame:CGRectMake(0, 44, 320, APP_SCREEN_HEIGHT-43-44)];
            isDownloadedByPopup=NO;
            [textlb setTitle:@"0 Photos Selected"];
            [saveBtn setEnabled:NO];
            [listOfFlags removeAllObjects];
            
            for (int i=0; i<imageListArray.count; i++) {
                [listOfFlags addObject:@"0"];
            }
            
            [self.navigationController setNavigationBarHidden:YES animated:NO];
            [saveMultiToolBar setHidden:NO];
            [gridView reloadData];
            break;
            
        case CANCEL_SAVE_MULTIPLE:
            [editBar setHidden:YES];
            [Utilities showTabBar:self.tabBarController];
            [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [saveMultiToolBar setHidden:YES];
            isMultipleSelection = NO;
            [gridView setEnableMultipleSelection:NO];
            
            [listOfFlags removeAllObjects];
            for (int i = 0; i < imageListArray.count; i++){
                [listOfFlags addObject:@"0"];
            }
            
            [gridView reloadData];
            [TestFlight passCheckpoint:@"Cancel to Save Multiple"];
            break;
            
        case CONFIRM_SAVE_MULTIPLE:
            [editBar setHidden:YES];
            downloadPurpose= DownloadForAddToFavorite;
            [saveMultiToolBar setHidden:YES];
            [Utilities showTabBar:self.tabBarController];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];

            [[LoadingView sharedInstance] showLoadingView];
            isMultipleSelection = NO;
            [gridView setEnableMultipleSelection:NO];
            [sender setEnabled:NO];
            numberOfDownloadedFile = 0;
            NSMutableArray *itemArray=[[NSMutableArray alloc] init];
            for (int index=0;index<listOfFlags.count;index++) {
                if ([[listOfFlags objectAtIndex:index] isEqualToString:@"1"]) {
                    Photo * photo = [self photoAtIndex:index];
                    [photo setPhotoCreatedDate:[Utilities uniqueStringWithPrefix:@""]];
                    [itemArray addObject:[photo itemObject]];
                }
            }
            [DatabaseConnection writeListItems:itemArray toEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            [itemArray release];
            [[LoadingView sharedInstance] stopLoadingView];
            [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [saveMultiToolBar setHidden:YES];
            [gridView reloadData];
            break;
            
        case OPTIONS_BUTTON:
            actionSheet=[[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:@"Cancel"
                                      destructiveButtonTitle:nil
                                           otherButtonTitles:@"Export To Phone Gallery",@"Email", nil];
            [actionSheet setTag:OPTIONS_BUTTON];
            [actionSheet showFromToolbar:editBar];
            [actionSheet release];
            break;
        case COPY_BUTTON:
            [self downloadSelectedImageForPurpose:DownloadForCopy];
            break;
        default:
            break;
    }
}
#pragma mark - Downloading For Sharing
-(void)downloadSelectedImageForPurpose:(DownloadPurpose)purpose{
    
    [[NSFileManager defaultManager] removeItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Downloads"] error:nil];

    downloadPurpose=purpose;
    [[LoadingView sharedInstance] showLoadingView];
    [gridView setMultipleTouchEnabled:NO];

    numberOfDownloadedFile = 0;
    for (int index=0;index<listOfFlags.count;index++) {
        if ([[listOfFlags objectAtIndex:index] isEqualToString:@"1"]) {
            Photo * photo = (Photo*)[imageListArray objectAtIndex:index];
            [photo setPhotoRecentlyUsed:[Utilities uniqueStringWithPrefix:@""]];
            [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
            NSString * originalFileName = [photo.photoImage lastPathComponent];
            NSURL * fileURL = [NSURL URLWithString:photo.photoImage];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Document"] stringByAppendingPathComponent:originalFileName]]) {
                NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
                [fm copyItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Document"] stringByAppendingPathComponent:originalFileName]
                            toPath:[[[NSHomeDirectory() stringByAppendingPathComponent:@"Document"] stringByAppendingPathComponent:@"Downloads"] stringByAppendingPathComponent:originalFileName]
                             error:nil];
            }
            else{
                DownloadHelper * downloadHelper = [[DownloadHelper alloc] init];
                
                [downloadHelper downloadFile:originalFileName
                            toFolderWithName:@"Downloads"
                                     withURL:fileURL
                      andSuccessNotification:[NSString stringWithFormat:@"DownloadForShareSuccess|%@",originalFileName]
                         andFailNotification:[NSString stringWithFormat:@"DownloadForShareFail|%@",originalFileName]];
                numberOfDownloadedFile++;
                
                [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(downloadFinished:)
                                                             name:[NSString stringWithFormat:@"DownloadForShareSuccess|%@",originalFileName]
                                                           object:nil];
                [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(downloadFailed:)
                                                             name:[NSString stringWithFormat:@"DownloadForShareFail|%@",originalFileName]
                                                           object:nil];
            }
        }
    }
    
    if (numberOfDownloadedFile == 0) {
    
        [self doneDownload:purpose];
    }
    
}

-(void)doneDownload:(DownloadPurpose)purpose{
    if (purpose==DownloadForAddToFavorite) {
        return;
    }
    
    [[LoadingView sharedInstance] stopLoadingView];
    [Utilities showTabBar:self.tabBarController];
    [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [saveMultiToolBar setHidden:YES];
    [gridView reloadData];
    isMultipleSelection = NO;
    [gridView setEnableMultipleSelection:NO];
    [editBar setHidden:YES];

    
    [listOfFlags removeAllObjects];
    for (int i = 0; i < imageListArray.count; i++){
        [listOfFlags addObject:@"0"];
    }
    

    
    NSArray *arr=[[NSFileManager defaultManager] subpathsAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Downloads"]];
//    NSMutableArray * resultArray=[[NSMutableArray alloc] init];
    NSMutableDictionary * resultDic=[[NSMutableDictionary alloc] init];
    for (NSString *str in arr) {
        UIImage *image=[UIImage imageWithContentsOfFile:[[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Downloads"] stringByAppendingPathComponent:str]];
        if (image) {
//            [resultArray addObject:image];
            [resultDic setValue:image forKey:str];
        }
        [image release];
    }

    switch (downloadPurpose) {
        case DownloadForCopy:
        [[UIPasteboard generalPasteboard] setImages:[resultDic allValues]];
            break;
        case DownloadForEmail:
            [self sendMail:resultDic];
            break;
        case DownloadForExport:
            if (listImageToExport) {
                [listImageToExport release];
                listImageToExport=nil;
            }
            listImageToExport=[[NSMutableArray alloc] init];
            listImageToExport=[[resultDic allValues] mutableCopy];
            [self writeListImageToGallery];
            break;
            
        default:
            break;
    }
    downloadPurpose = DownloadForAddToFavorite;
}


#pragma mark - Downloading To Favorites Folder Notification

- (void)downloadFinished:(NSNotification*)notifier
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notifier.name object:nil];
    if (isDownloadedByPopup) {
        
        if (![[[(Photo*)[imageListArray objectAtIndex:selectedCellIndex] photoImage] lastPathComponent] isEqualToString: [[[notifier.name componentsSeparatedByString:@"|"] lastObject] lastPathComponent] ]) {
            return;
        }
  
        DBLOG(@"selected btn:%d",popupBtnTagClicked);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.image = [self imageAtIndex:selectedCellIndex];
        isDownloadedByPopup=NO;
        isDownloaded=DownloadSuccess;

        if (popupBtnTagClicked==-1) {
            return;
            
        }
        else {
            [self popupDidSelectBtnTag:popupBtnTagClicked];
            
        }
        
        return;
    }
    numberOfDownloadedFile--;
    if (numberOfDownloadedFile == 0) {
        [[LoadingView sharedInstance] stopLoadingView];
        [Utilities showTabBar:self.tabBarController];

        [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [saveMultiToolBar setHidden:YES];
        [gridView reloadData];
        for (int i = 0; i < imageListArray.count; i++){
            [listOfFlags addObject:@"0"];
        }
//        [TestFlight passCheckpoint:@"Save Multiple successfully"];
        [self doneDownload:downloadPurpose];
        [editBar setHidden:YES];

    }
    DBLOG(@"DownloadFinish:%d",numberOfDownloadedFile);

}

- (void)downloadFailed:(NSNotification*)notifier
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notifier.name object:nil];
    if (isDownloadedByPopup) {

        isDownloadedByPopup = NO;
        isDownloaded = DownloadFailed;
        return;
    }
    
    numberOfDownloadedFile--;
    if (numberOfDownloadedFile == 0) {
        [Utilities showTabBar:self.tabBarController];
        [[LoadingView sharedInstance] stopLoadingView];
        [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [saveMultiToolBar setHidden:YES];
        [gridView reloadData];
        for (int i = 0; i < imageListArray.count; i++)
            [listOfFlags addObject:@"0"];
        [self doneDownload:downloadPurpose];
        [editBar setHidden:YES];
    }

//    [TestFlight passCheckpoint:@"Save Multiple fail"];
//    DBLOG(@"Save multiple failed: %@", [((NSError*)notifier.object) description]);
    DBLOG(@"DownloadFail:%d",numberOfDownloadedFile);

}

#pragma mark - Grid View Data Source

- (NSString*)gridView:(UIGridView *)gridView imageURLStringOfCellAtIndex:(NSInteger)cellIndex
{
    return ((Photo*)[imageListArray objectAtIndex:cellIndex]).photo250URL;
}

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    return [imageListArray count];
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{
    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    if ([imageListArray count] == 0) {
        return nil;
    }
    Photo * photo = [imageListArray objectAtIndex:cellIndex];
    [cell setImageURLString:photo.photoThumbnail];
    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.textLabel setHidden:YES];
    if (isMultipleSelection) {
        if ([[listOfFlags objectAtIndex:cellIndex] isEqualToString:@"1"]) {
            [cell setAccessoryType:UIGridViewCellAccessorySelected];
            [cell setIsSelected:YES];
        }
        else {
            [cell setAccessoryType:UIGridViewCellAccessoryNone];
            [cell setIsSelected:NO];
        }
    }
    else{
        if (selectedCellIndex == cellIndex) {
            [cell setIsSelected:YES];
            [cell setAccessoryType:UIGridViewCellAccessoryGlow];
        }
        else
        {
            [cell setIsSelected:NO];
            [cell setAccessoryType:UIGridViewCellAccessoryNone];
        }
    }
    
    return cell;
}

#pragma mark - Grid View Delegate


- (void)gridView:(UIGridView *)_gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{

    if (!isMultipleSelection)
    {   //  If single select mode, push to ImageDetailViewController
        
        if (![self imageAtIndex:cellIndex]) {
            
            DownloadHelper * downloadHelper = [[DownloadHelper alloc] init];
            
            [downloadHelper downloadFile:[[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage] lastPathComponent]
                        toFolderWithName:nil
                                 withURL:[NSURL URLWithString:[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage]]
                  andSuccessNotification:[NSString stringWithFormat:@"Success|%@",[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage]]
                     andFailNotification:[NSString stringWithFormat:@"Fail|%@",[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage]]];
            
            
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(downloadFinished:)
                                                         name:[NSString stringWithFormat:@"Success|%@",[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage]]
                                                       object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(downloadFailed:)
                                                         name:[NSString stringWithFormat:@"Fail|%@",[(Photo*)[imageListArray objectAtIndex:cellIndex] photoImage]]
                                                       object:nil];
            
            isDownloadedByPopup=YES;
            isDownloaded =DownloadProcessing;
            


        }
        else {
            DBLOG(@"File Exist!");
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.image = [self imageAtIndex:cellIndex];
            isDownloadedByPopup=NO;
            isDownloaded = DownloadSuccess;
            

        }
        
        Photo *photo=[imageListArray objectAtIndex:cellIndex];
        [photo setPhotoRecentlyUsed:[Utilities uniqueStringWithPrefix:@""]];
        
        [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
        
        CGPoint offsetPoint = gridView.contentOffset;
        DBLOG(@"offset point: %f, %f", offsetPoint.x, offsetPoint.y);
        
        CGRect frame = [[gridView cellAtIndex:cellIndex] frame];
        
        [popUpBar setSelectedFrame:CGRectMake(frame.origin.x - offsetPoint.x, 
                                              frame.origin.y - offsetPoint.y, 
                                              frame.size.width, 
                                              frame.size.height)];
        GridViewCell * cell = [gridView cellAtIndex:cellIndex];
        [cell setIsSelected:YES];
        [cell setAccessoryType:UIGridViewCellAccessoryGlow];
        
        if ([[DatabaseConnection getFavoritePhotoWithID:[photo photoID]] count]>0) {
            [popUpBar setStatusOfFavoriteButtonAsActive:YES];

        }
        else {
            [popUpBar setStatusOfFavoriteButtonAsActive:NO];
        }

        
        if (selectedCellIndex == cellIndex)
        {
            [popUpBar.view setHidden:!popUpBar.view.hidden];
        }
        else {
            [popUpBar.view setHidden:NO];
        }
        selectedCellIndex = cellIndex;
        popupBtnTagClicked=-1;
        
        
    }
    else 
    {   //  If multiple select mode, 
        if ([[listOfFlags objectAtIndex:cellIndex] isEqualToString:@"1"]) {
            [listOfFlags replaceObjectAtIndex:cellIndex withObject:@"0"];
        }
        else{
            [listOfFlags replaceObjectAtIndex:cellIndex withObject:@"1"];
        }
        int count=0;
        for (int i=0; i<listOfFlags.count; i++) {
            if ([[listOfFlags objectAtIndex:i] isEqualToString:@"1"]) {
                count++;
            }
        }
        if (count>0) {
            [saveBtn setEnabled:YES];
            [copyBtn setEnabled:YES];
            [copyBtn setTitle:[NSString stringWithFormat:@"Copy (%d)",count]];
            
        }
        else{
            [saveBtn setEnabled:NO];
            [copyBtn setEnabled:NO];
        }
        
        if (count>5) {
            [copyBtn setTitle:[NSString stringWithFormat:@"Copy"]];
            [copyBtn setEnabled:NO];
        }
        
        [textlb setTitle:[NSString stringWithFormat:@"%d Photos Selected",count]];
        
    }
}


- (void)gridViewDidScroll:(UIGridView *)gridView
{
    // Hide pop up menu when scrolling
    if (!popUpBar.view.hidden) {
        [popUpBar.view setHidden:YES];
    }
}

#pragma mark -

-(void)resetListOfFlags{

}

#pragma mark - Pop Up Bar Delegate

- (void)popUpBar:(PopUpViewController *)popUpController didSelectButton:(id)sender
{
//    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showLoadingView];

    DBLOG(@"image isdownloaded:%d",isDownloaded);
    
    if (isDownloaded==DownloadSuccess || [sender tag]==2  ||[sender tag]==1) {
        [self popupDidSelectBtnTag:[sender tag]];
    }
    else {
        popupBtnTagClicked=[sender tag];
    }
    
    if ([sender tag] != 1) {
        [popUpBar.view setHidden:YES];
    }
}

-(void)popupDidSelectBtnTag:(int)tag{
    
    
    [[LoadingView sharedInstance] stopLoadingView];
    
    DBLOG(@"popupDidSelectBtnTag:%d",tag);
    copyLabel.hidden=NO;
    copyLabel.text=@"Image Copied!";
    ImageDetailViewController * detailView;
    switch (tag) {
        case 0:
            DBLOG(@"Share");
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            break;
            
        case 1:

            if ([DatabaseConnection isAddedToFavoriteWithPhotoID:[[self photoAtIndex:selectedCellIndex] photoID]]) {
                [popUpBar setStatusOfFavoriteButtonAsActive:NO];
                
                [DatabaseConnection deleteListItems:[NSMutableArray arrayWithObject:[[self photoAtIndex:selectedCellIndex] itemObject]] fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            }
            else {
                [popUpBar setStatusOfFavoriteButtonAsActive:YES];
                Photo *photo=[self photoAtIndex:selectedCellIndex];
                [photo setPhotoCreatedDate:[Utilities uniqueStringWithPrefix:@""]];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            }
            break;
            
        case 2:
            DBLOG(@"View detail");
            detailView = [[ImageDetailViewController alloc] init];
            [detailView setItemList:imageListArray];
            [detailView setItemIndex:selectedCellIndex];
            [detailView setItemType:@"item"];
//            self.navigationItem.title=@"Back";
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];
            break;
            
        default:
            break;
    }
    if (tag==3) {
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageAtIndex:selectedCellIndex]];
        [self presentModalViewController:mcvc animated:YES];
    }
}
#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([actionSheet tag]==0) {
        if (buttonIndex==0) {
            
            [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            isMultipleSelection = NO;
            UIImageWriteToSavedPhotosAlbum([self imageAtIndex:selectedCellIndex], nil,nil,nil);
            return;
        }
        if (buttonIndex==1) {
            
//            [self sendMail];
            
            
            return;
        }
    }
    if ([actionSheet tag]==OPTIONS_BUTTON) {
        if (buttonIndex==0) {
            [self downloadSelectedImageForPurpose:DownloadForExport];
        }
        else if (buttonIndex==1){
            [self downloadSelectedImageForPurpose:DownloadForEmail];
        }
        else if (buttonIndex==2){
            [Utilities showTabBar:self.tabBarController];
            [gridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [saveMultiToolBar setHidden:YES];
            for (int i = 0; i < imageListArray.count; i++){
                [listOfFlags addObject:@"0"];
            }
            [gridView reloadData];
            [editBar setHidden:YES];
        }
    }
}

- (UIImage *)imageAtIndex:(NSUInteger)index {
    DBLOG(@"ImageListViewController - imageAtIndex:%d",index);
    Photo *photo = [imageListArray objectAtIndex:index];
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fm=[[NSFileManager alloc] init];
    if ([fm fileExistsAtPath:documentPath]) {
        return [UIImage imageWithContentsOfFile:[documentPath stringByAppendingPathComponent:[[photo photoImage] lastPathComponent]]];
    }
    else {
        return nil;
    }
}


#pragma mark - MFMailComposeViewController Delegate

-(void)sendMail:(NSMutableDictionary*)_imageList{
    
    if ([MFMailComposeViewController canSendMail]) {
        
        // Fill out the email body text
        //Create a string with HTML formatting for the email body
        NSString *iTunesLink = @"itms-apps://itunes.com/apps/reacticons"; // replate it with yours
        NSString *emailBody =
        [NSString stringWithFormat:@"\n<p>Sent from Reacticons! ...an gallery app of all reaction images.</br> <a href = '%@'>Download</a> it now!</p>", iTunesLink];

        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;
//        [emailDialog setSubject:@"My Inline Image Document"];
        [emailDialog setMessageBody:emailBody isHTML:YES];
        
        //Pick an image to insert
        //This example would come from the main bundle, but your source can be elsewhere
        for (NSString *key in [_imageList allKeys]) {
            
            
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([_imageList objectForKey:key])];
            
            [emailDialog addAttachmentData:imageData mimeType:@"png" fileName:key];
            
        }
        
        
        [self presentModalViewController:emailDialog animated:YES];
        [emailBody release];
        
        
    }
    else {
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Cannot Send Via Mail" message:@"Please setup your mail before share via Email" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    
}

-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {

        [controller dismissViewControllerAnimated:YES completion:^{
            
        }];
    
}

-(void)writeListImageToGallery{
    if ([listImageToExport count]>0) {
        UIImage *image=[[listImageToExport objectAtIndex:0] copy];
        UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
        [listImageToExport removeObjectAtIndex:0];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
//    DBLOG(@"error:%@",[error localizedDescription]);
    [self writeListImageToGallery];
}

-(Photo*)photoAtIndex:(NSUInteger)_index{
    Photo *photo=[[Photo alloc] init];
    [photo parseFromItem:[[imageListArray objectAtIndex:_index] itemObject]];
    return [photo autorelease];
}



@end
